package com.ossean.projectmanager.hotwords;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ossean.projectmanager.lasttabledao.HotwordDao;
import com.ossean.projectmanager.lasttabledao.PointersDao;
import com.ossean.projectmanager.lasttabledao.TagDao;
import com.ossean.projectmanager.lasttabledao.TaggingsDao;
import com.ossean.projectmanager.model.Hotword;
import com.ossean.projectmanager.model.OpenSourceProject;

@Component("inserthotwords")
public class InsertHotwords {

	@Resource
	private HotwordDao hotwordsDao;
	@Resource
	private PointersDao pointersDao;
	@Resource
	private TagDao tagsDao;
	@Resource
	private TaggingsDao taggingsDao;
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void insert(List<Hotword> hotwordsList, String sourceTableName, String targetTableName, int pointer, List<String> updateDisagreeNumTagNameList, Map<String, Integer> tagCountMap, OpenSourceProject project){
		int count = 0;//用于纪录插入了多少个热词
		for(int i = 0; i < hotwordsList.size() && count < 20; i++){
			Hotword hotwords = hotwordsList.get(i);
			//首先检查该osp_id和name的hotwords记录是否存在
			List<Hotword> tmp = hotwordsDao.findItem(hotwords);
			if(tmp.size() != 0){
				//表示当前的记录存在
				continue;
			}
			//循环插入每一个hotwords对象
			hotwordsDao.insertItem(hotwords);
			count++;
		}
		
		//修改需要增加disagree_num的词频
		for(int i = 0; i < updateDisagreeNumTagNameList.size(); i++){
			String tagName = updateDisagreeNumTagNameList.get(i);
			//根据tagName查找tagId
			List<Integer> ids = tagsDao.getIdByName(tagName);
			if(ids.size() == 0){
				//表示并不存在该标签 需要在tags表中增加这条记录
				tagsDao.insertTag(tagName);
				i--;
				continue;
			}
			int tag_id = ids.get(0);
			int taggable_id = project.getId();
			String taggable_type = "OpenSourceProject";
			int value = taggingsDao.getDisagreeNum(tag_id, taggable_id, taggable_type);
			value = value + tagCountMap.get(tagName);//增加标签在帖子中出现的次数
			taggingsDao.updateDisagreeNum(value, taggable_id, taggable_type, tag_id);
		}
		
		pointersDao.updatePointer(sourceTableName, targetTableName, pointer);
	}
}
